package com.finance.system.user.controller;

import com.finance.system.user.entity.AuthInbound;
import com.finance.system.user.entity.PhoneRegistryInbound;
import com.finance.system.user.entity.UserEntity;
import com.finance.system.user.entity.UserExtendEntity;
import com.finance.system.user.exception.AuthException;
import com.finance.system.user.service.IUserExtendService;
import com.finance.system.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Map;

@Api(description = "用户模块",tags = "认证")
@RestController
@RequestMapping("auth")
@Validated
public class AuthController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserExtendService userExtendService;

    @ApiOperation("手机注册新用户")
    @PostMapping("registryWithPhone")
    public void registryWithPhone(@RequestBody PhoneRegistryInbound param){
        if(!checkVerifyCodeSuccess(param.getPhone(),param.getVerifyCode())) throw AuthException.verifyCodeErrorException();

        UserEntity user = userService.getByPhone(param.getPhone());
        if(user != null) throw AuthException.userHasExistException();

        user = new UserEntity()
                .setPhone(param.getPhone())
                .setCreateAt(LocalDateTime.now())
                .setNickName(RandomStringUtils.randomAscii(20));
        userService.save(user);

        UserExtendEntity extendEntity = new UserExtendEntity()
                .setUserId(user.getId())
                .setHeadImage("http://cdn.duitang.com/uploads/item/201410/21/20141021130151_ndsC4" +
                        ".jpeg");
        userExtendService.save(extendEntity);

    }


    @ApiOperation("用户登陆认证")
    @PostMapping
    public void auth(@RequestBody AuthInbound param){
        System.out.println(param.toString());
    }


    private boolean checkVerifyCodeSuccess(String phone, String verifiyCode) {
        return true;
    }
}
